import { api, TWsClient } from '@/assets/api';
class TTsJumpUtils {
    constructor() {}
    ms2Ticker(t) {
        var me = this;
        var res = "";
        try {
            var ms = t % 1000;
            var s = Math.floor(t / 1000.0) % 60;
            var m = Math.floor(t / 1000.0 / 60) % 60;
            var h = Math.floor(t / 1000.0 / 60 / 60) % 24;
            //var tt = ms + s * 1000 + m * 60 * 1000 + h * 3600 * 1000

            ms = ms + '000'
            s = '00' + s
            m = '00' + m
            h = '00' + h
            res = h.substring(h.length - 2, h.length) +
                ":" + m.substring(m.length - 2, m.length) +
                ":" + s.substring(s.length - 2, s.length) +
                "." + ms.substring(0, 3);
        } catch (error) {
            console.log(error)
        }
        return res;
    }
    ms2Second(ms, decSize = 2, decCarry = 0) {
        var me = this;
        var res = 0;
        try {
            var v = me.fixed(ms * 0.001, decSize, decCarry);
            res = parseFloat(v);
        } catch (error) {
            console.log(error)
        }
        return res;
    }
    fixed(floatValue, decSize = 2, decCarry = 0) {
        var me = this;
        var res = '';
        try {
            var fun = ([Math.floor, Math.ceil, Math.round])[decCarry];
            var v = floatValue;
            if (decSize > 0) {
                for (var i = 0; i < decSize; i++) {
                    v = v * 10.0;
                }
                v = fun(v)
                for (var i = 0; i < decSize; i++) {
                    v = v * 0.1;
                }
                var pos = (v + '').indexOf('.');
                var vs = ""
                if (pos < 0) {
                    vs = v + ".000"
                    pos = (v + '').length
                } else {
                    vs = v + "000"
                }
                var vs = vs.substring(0, pos) + "." + vs.substring(pos + 1, pos + 1 + decSize);
                res = vs;
            } else {
                res = fun(floatValue) + '';
            }
        } catch (error) {
            console.log(error)
        }
        return res;
    }
}

const tsUtils = new TTsJumpUtils();

class TTsJumpSplitSettings {
    constructor() {
        this.settingsInfo = {
            reverseFlag: 1,
            secondAllow: 45,
            secondBest: 45,
            secondLimited: 45,

            penScoreRefuse: 4,
            penScoreFail: 4,
            penSecond: 6,
            penTimeoutSecond: 1,
            penTimeoutScore: 0.4,

            scoreDecSize: 1,
            scoreDecCarry: 1,
            timeDecSize: 2,
            timeDecCarry: 0,
        };
    }
}
class TTsJumpSplit {
    constructor(_core, _code) {
        this.core = _core;
        this.code = _code;
        this.info = {
            start: 0,
            end: 0,
            pause: [],
            failScore: 0,
            refuseScore: 0,
            delaySecond: 0,
            irm: ""
        }
    }
    get settingsInfo() {
        var me = this;
        return me.core.settings[me.code].settingsInfo;
    }
    get times() {
        return this.core.times;
    }
    get isStartd() {
        var me = this;
        var res = false;
        try {
            res = me.info.start > 0;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get isActive() {
        var me = this;
        var res = false;
        try {
            res = me.info.start > 0 && me.info.end == 0;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get isEnd() {
        var me = this;
        var res = false;
        try {
            res = me.info.end == 0;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get isPause() {
        var me = this;
        var res = false;
        try {
            if (me.info.start > 0 && me.info.end == 0 && me.info.pause.length > 0) {
                res = me.info.pause[me.info.pause.length - 1].end == 0;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get isRunning() {
        var me = this;
        var res = false;
        try {
            if (me.isActive) {
                res = !me.isPause;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get isOverTime() {
        var me = this;
        var res = false;
        try {
            res = me.netTime > 1000 * me.settingsInfo.secondAllow;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get isOverLimitedTime() {
        var me = this;
        var res = false;
        try {
            res = me.netTime >= 1000 * me.settingsInfo.secondLimited;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get isOverLimitedTimeAndNotEnd() {
        var me = this;
        var res = false;
        try {
            res = me.netTime >= 1000 * me.settingsInfo.secondLimited && me.info.end == 0;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get status() {
        var me = this;
        var res = 0;
        try {
            if (me.info.end > 0) {
                res = 3;
            } else if (me.info.start > 0) {
                res = me.isPause ? 2 : 1;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get statusName() {
        var me = this;
        var res = 0;
        try {
            if (me.info.irm == '') {
                res = (['等待', '进行中', '暂停', '完成'])[me.status]
            } else {
                res = me.info.irm;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get endTime() {
        var me = this;
        var res = 0;
        try {
            if (me.info.end > 0) {
                res = me.info.end
            } else {
                res = me.info.start == 0 ? 0 : me.times.nowTime;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get pauseTime() {
        var me = this;
        var res = 0;
        try {
            if (me.info.pause.length > 0) {
                me.info.pause.forEach(p => {
                    var endTm = p.end == 0 ? me.endTime : p.end;
                    res = res + endTm - p.start;
                })
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get netTime() {
        var me = this;
        var res = 0;
        try {
            if (me.info.start > 0) {
                res = me.endTime - me.info.start - me.pauseTime + 1000 * me.info.delaySecond;
                if (res < 0) {
                    res = 0;
                } else {
                    var maxTm = 1000 * me.settingsInfo.secondLimited;
                    if (res > maxTm) {
                        res = maxTm;
                    }
                }
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get overTime() {
        var me = this;
        var res = 0;
        try {
            if (me.isOverTime) {
                res = me.netTime - 1000 * me.settingsInfo.secondAllow
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get penRefuse() {
        var me = this;
        var res = 0;
        try {
            res = me.info.refuseScore;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get penFail() {
        var me = this;
        var res = 0;
        try {
            res = me.info.failScore;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get penPoint() {
        var me = this;
        var res = 0;
        try {
            res = me.penFail + me.penRefuse;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get penTime() {
        var me = this;
        var res = 0;
        try {
            if (me.info.start > 0) {
                var overTime = me.overTime;
                if (overTime > 0) {
                    var rate = overTime * 0.001 / me.settingsInfo.penTimeoutSecond;
                    var fun = ([Math.floor, Math.ceil, Math.round])[me.settingsInfo.timeDecCarry]
                    var v = fun(rate) * me.settingsInfo.penTimeoutScore;
                    //res = me.core.formatFix(v, me.settingsInfo.scoreDecSize, me.settingsInfo.scoreDecCarry);
                    //res = me.core.formatFixStr(v, me.settingsInfo.scoreDecSize);
                    res = tsUtils.fixed(v, me.settingsInfo.scoreDecSize, 2);
                }
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get penTotal() {
        var me = this;
        var v = me.penRefuse + me.penFail + parseFloat(me.penTime);
        v = tsUtils.fixed(v, me.settingsInfo.scoreDecSize, me.settingsInfo.scoreDecCarry);
        return parseFloat(v);
    }
    get dispSecond() {
        var me = this;
        var res = 0;
        try {
            var v = me.settingsInfo.reverseFlag > 0 ? me.settingsInfo.secondAllow * 1000 - me.netTime : me.netTime;
            res = tsUtils.fixed(v * 0.001, me.settingsInfo.timeDecSize, me.settingsInfo.timeDecCarry);
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get dispPauseSecond() {
        var me = this;
        var res = 0;
        try {
            var v = me.settingsInfo.reverseFlag > 0 ? me.settingsInfo.secondAllow * 1000 - me.netTime : me.netTime;
            res = tsUtils.fixed(me.pauseTime * 0.001, me.settingsInfo.timeDecSize, me.settingsInfo.timeDecCarry);
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get dispOverTime() {
        var me = this;
        var res = 0;
        try {
            var max = me.settingsInfo.secondLimited * 1000;
            var v = me.overTime;
            v = v > max ? max : v;
            res = tsUtils.fixed(v * 0.001, me.settingsInfo.timeDecSize, me.settingsInfo.timeDecCarry);
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get dispStartTime() {
        var me = this;
        var res = '';
        try {
            if (me.info.start > 0) {
                res = tsUtils.ms2Ticker(me.info.start);
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get dispEndTime() {
        var me = this;
        var res = '';
        try {
            if (me.info.end > 0) {
                res = tsUtils.ms2Ticker(me.info.end);
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get enableStart() {
        var me = this;
        var res = false;
        try {
            if (me.info.start == 0) {
                res = true;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get enablePause() {
        var me = this;
        var res = false;
        try {
            if (me.info.start > 0 && me.info.end == 0 && !(me.isPause)) {
                res = true;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get enableResume() {
        var me = this;
        var res = false;
        try {
            if (me.isPause) {
                res = true;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    get enableEnd() {
        var me = this;
        var res = false;
        try {
            if (me.info.start > 0 && me.info.end == 0) {
                res = true;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }


    trigger(acCode, acTime, value, tag) {
        var me = this;
        try {
            me.core.doOnSplitAction(me, acCode, acTime, value, tag)
        } catch (error) {
            console.log(error);
        }
    }
    reset() {
        var me = this;
        try {
            me.info = {
                start: 0,
                end: 0,
                pause: [],
                failScore: 0,
                refuseScore: 0,
                delaySecond: 0,
                irm: ""
            };
            me.trigger("reset", me.times.nowTime, 0, {});
        } catch (error) {
            console.log(error);
        }
    }
    start(acTime) {
        var me = this;
        try {
            if (me.info.start == 0) {
                /*
                me.info.start = acTime;
                me.trigger("start", acTime, 0, {});
                */
                me.forceSetStartTime(acTime)
            }
        } catch (error) {
            console.log(error);
        }
    }
    end(acTime) {
        var me = this;
        try {
            if (me.info.start > 0 && me.info.end == 0) {
                if (me.isPause) {
                    me.info.pause[me.info.pause.length - 1].end = acTime;
                }
                /*
                me.info.end = acTime;
                me.trigger("end", acTime, 0, {});
                */
                me.forceSetEndTime(acTime);
            }
        } catch (error) {
            console.log(error);
        }
    }
    switchPause(acTime) {
        var me = this;
        try {
            if (me.info.start > 0 && me.info.end == 0) {
                if (me.isPause) {
                    me.info.pause[me.info.pause.length - 1].end = acTime;
                    me.trigger("resume", acTime, 0, {});
                } else {
                    me.info.pause.push({
                        start: acTime,
                        end: 0
                    });
                    me.trigger("pause", acTime, 0, {});
                }
            }
        } catch (error) {
            console.log(error);
        }
    }
    setRefuseScore(acTime, score) {
        var me = this;
        try {
            me.info.refuseScore = score;
            me.trigger("refuserScore", acTime, score, {});
        } catch (error) {
            console.log(error);
        }
    }
    setFailScore(acTime, score) {
        var me = this;
        try {
            me.info.failScore = score;
            me.trigger("failScore", acTime, score, {});
        } catch (error) {
            console.log(error);
        }
    }
    setDelaySecond(acTime, second) {
        var me = this;
        try {
            me.info.delaySecond = second;
            me.trigger("delaySecond", acTime, second, {});
        } catch (error) {
            console.log(error);
        }
    }
    setPenScore(acTime, scoreKey, value) {
        var me = this;
        try {
            if (scoreKey == 'failScore') {
                me.setFailScore(acTime, value)
            } else if (scoreKey == 'refuseScore') {
                me.setRefuseScore(acTime, value)
            }
            if (scoreKey == 'delaySecond') {
                me.setDelaySecond(acTime, value)
            }
        } catch (error) {
            console.log(error);
        }
    }
    forceSetStartTime(acTime) {
        var me = this;
        try {
            var oldTime = me.info.start;
            me.info.start = acTime;
            me.trigger("start", acTime, 0, { oldStartTime: oldTime });
        } catch (error) {
            console.log(error);
        }
    }
    forceSetEndTime(acTime) {
        var me = this;
        try {
            var oldTime = me.info.end;
            me.info.end = acTime;
            me.trigger("end", acTime, 0, {});
            /*
            if (acTime > 0) {
                me.trigger("end", acTime, 0, {});
            } else {
                me.trigger("forceSetEndTime", acTime, 0, { oldEndTime: oldTime });
            }
            */
        } catch (error) {
            console.log(error);
        }
    }
    getMaxEndTime() {
        var me = this;
        var res = 0;
        try {
            if (me.info.start > 0) {
                res = me.info.start + me.settingsInfo.secondLimited * 1000 + me.pauseTime - 1000 * me.info.delaySecond;
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    getStaticInfo() {
        var me = this;
        var res = {};
        try {
            res = {
                irm: me.info.irm,
                status: me.status,

                pauseTime: me.pauseTime,
                netTime: me.netTime,
                overTime: me.overTime,

                dispSecond: me.dispSecond,
                penFail: me.penFail,
                penTime: me.penTime,
                penRefuse: me.penRefuse,
                penTotal: me.penTotal,

                isOverLimitedTime: me.isOverLimitedTime ? 1 : 0,
                isOverLimitedTimeAndNotEnd: me.isOverLimitedTimeAndNotEnd ? 1 : 0,
            };
        } catch (error) {
            console.log(error);
        }
        return res;
    }
}
class TTsJumpTimes {
    constructor(_core) {
        this.core = _core;
        this.dev = (new Date()).getTime();
        this.local = (new Date()).getTime();
    }
    get nowTime() {
        var res = 0;
        var me = this;
        try {
            res = (new Date()).getTime() - me.local + me.dev;
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    setDeviceTime(acTime) {
        var me = this;
        try {
            me.dev = acTime;
            me.local = (new Date()).getTime();
        } catch (error) {
            console.log(error);
        }
    }
}
class TTsJumpCore {
    constructor() {
        this.resultId = 0;
        this.utils = new TTsJumpUtils();
        this.settings = {
            matchFormat: "",
            t0: new TTsJumpSplitSettings(),
            t1: new TTsJumpSplitSettings(),
            t2: new TTsJumpSplitSettings(),
        };
        this.splits = {
            t0: new TTsJumpSplit(this, 't0'),
            t1: new TTsJumpSplit(this, 't1'),
            t2: new TTsJumpSplit(this, 't2'),
        };
        this.times = new TTsJumpTimes(this);
        this.splitLogs = [];
        this.signalLogs = [];

        this.onAction = (split, acCode, acTime, value, tag) => {
            //console.log(split, acCode, acTime, value, tag);
        }
    }

    get hasSplit2() {
        var me = this;
        var res = false;
        try {
            var types = ["2PSP--", "2P----"];
            res = types.includes(me.settings.matchFormat);
        } catch (error) {
            console.log(error)
        }
        return res;
    }

    enableStartSplit2() {
        var me = this;
        var res = false;
        try {
            var flag = me.splits.t1.end > 0 && me.splits.t2.start == 0 && me.splits.t1.info.irm == '' && me.splits.t2.info.irm == '';
            if (flag) {
                if (me.settings.settingsInfo.matchFormat == '2PSP--') {
                    res = !(me.splits.t1.isOverLimitedTime);
                } else if (me.settings.settingsInfo.matchFormat == '2P----') {
                    var penFlag = me.splits.t1.info.failScore > 0 ||
                        me.splits.t1.info.refuseScore > 0 ||
                        me.splits.t1.isOverTime;
                    res = !penFlag;
                }
            }
        } catch (error) {
            console.log(error);
        }
        return res;
    }
    init(resultId) {
        var me = this;
        return new Promise((su, fa) => {
            try {
                me.resultId = resultId;
                su();
            } catch (error) {
                console.log(error);
                su();
            }
        })
    }
    loadStatus() {
        var me = this;
        try {
            var localKey = 'jumpTs2025_info_' + me.resultId;
            var content = window.localStorage.getItem(localKey);
            //console.log(content)
            if (content != null && content.length > 0) {
                var status = JSON.parse(content);
                me.splits.t0.info = status.splitInfos.t0;
                me.splits.t1.info = status.splitInfos.t1;
                me.splits.t2.info = status.splitInfos.t2;
                me.signalLogs = status.signalLogs;
                me.splitLogs = status.splitLogs;
            }
        } catch (error) {
            console.log(error);
        }
    }
    saveStatus() {
        var me = this;
        try {
            var status = {
                splitInfos: {
                    t0: me.splits.t0.info,
                    t1: me.splits.t1.info,
                    t2: me.splits.t2.info,
                },
                signalLogs: me.signalLogs,
                splitLogs: me.splitLogs
            }
            var content = JSON.stringify(status);
            var localKey = 'jumpTs2025_info_' + me.resultId;
            window.localStorage.setItem(localKey, content);
        } catch (error) {
            console.log(error);
        }
    }
    setDeviceTime(devTime) {
        var me = this;
        try {
            me.times.setDeviceTime(devTime);
            if (me.splits.t0.isOverLimitedTimeAndNotEnd) {
                var acEndTime = me.splits.t0.getMaxEndTime();
                me.splits.t0.end(acEndTime);
                me.splits.t1.start(acEndTime);
            }
            if (me.splits.t1.isOverLimitedTimeAndNotEnd) {
                var acEndTime = me.splits.t1.getMaxEndTime();
                me.splits.t1.end(acEndTime);
            }
            if (me.splits.t2.isOverLimitedTimeAndNotEnd) {
                var acEndTime = me.splits.t2.getMaxEndTime();
                me.splits.t2.end(acEndTime);
            }
        } catch (error) {
            console.log(error);
        }
    };
    autoSetSplit2Start() {
        var me = this;
        try {
            console.log('check autoSetSplit2Start');
            if (me.settings.matchFormat.indexOf('2P') == 0) {
                var t1 = me.splits.t1;
                var t2 = me.splits.t2;
                if (t1.info.irm == '') {
                    var flag = false;
                    if (me.settings.matchFormat == '2PSP--') {
                        flag = t1.netTime < 1000 * t1.settingsInfo.secondLimited;
                    } else {
                        flag = !(
                            t1.info.refuseScore != 0 ||
                            t1.info.failScore != 0 ||
                            t1.info.refuseScore == 0 ||
                            t1.info.isOverTime);
                    }
                    if (flag) {
                        t2.forceSetStartTime(t1.info.end);
                        console.log('autoSetSplit2Start', t1.info.end);
                    }

                }
            }

        } catch (error) {
            console.log(error)
        }
    }
    doOnSplitAction(split, acCode, acTime, value, tag) {
        var me = this;
        try {
            me.splitLogs.push({
                splitCode: split.code,
                acCode,
                acTime,
                value,
                tag: tag
            })
            me.saveStatus();
            if (me.onAction != null) {
                me.onAction(split, acCode, acTime, value, tag);
            }
        } catch (error) {
            console.log(error);
        }
    }
    actionOnSignal(signalCode, acTime) {
        var me = this;
        try {
            var t0 = me.splits.t0;
            var t1 = me.splits.t1;
            var t2 = me.splits.t2;
            if (signalCode == 'C0') {
                t1.start(acTime);
            } else if (signalCode == 'C1') {
                t1.end(acTime);
            } else if (signalCode == 'C2') {
                t2.end(acTime);
            } else if (signalCode == 'C4') {
                if (t0.info.start == 0) {
                    t0.start(acTime);
                } else if (t0.info.start > 0 && t0.info.end == 0 && t1.info.start == 0) {
                    t0.switchPause(acTime);
                } else if (t1.info.start > 0 && t1.info.end == 0) {
                    t1.switchPause(acTime);
                } else if (t2.info.start > 0 && t2.info.end == 0) {
                    t2.switchPause(acTime);
                }
            }
        } catch (error) {
            console.log(error);
        }
    }
    getNotifyInfo() {
        var me = this;
        var res = {
            time: {
                dev: me.times.dev,
                local: me.times.local
            },
            settings: {
                matchFormat: me.settings.matchFormat,
                t0: me.settings.t0.settingsInfo,
                t1: me.settings.t1.settingsInfo,
                t2: me.settings.t2.settingsInfo,
            },
            infos: {
                t0: me.splits.t0.info,
                t1: me.splits.t0.info,
                t2: me.splits.t0.info,
            },
            statics: {
                t0: me.splits.t0.getStaticInfo(),
                t1: me.splits.t1.getStaticInfo(),
                t2: me.splits.t2.getStaticInfo()
            },
        };
        try {} catch (error) {
            console.log(error);
        }
        return res;
    }
    getPostResultInfo(split, splitResultId) {
        var me = this;
        var res = {
            ResultJson: "{}",
            DetailResult: "{}"
        };
        try {
            var penPoint = split.penRefuse + split.penFail;
            var penTime = split.penTime;
            var matchTime = split.dispSecond;
            var result = {
                ResultId: splitResultId,
                JumpPenalty: penPoint,
                MatchTime: matchTime,
                TimePenalty: penTime
            }
            var detailResult = {
                ResultId: splitResultId
            }
            res = {
                ResultJson: JSON.stringify(result),
                DetailResult: JSON.stringify(detailResult)
            };
        } catch (error) {
            console.log(error)
        }
        return res;
    }
}

class TTsJumpLedPaging {
    constructor() {
        this.timeout = 5000;
        this.lastTime = 0;
        this.pageIndex = 0;
        this.pageSize = 5;
        this.items = [];
        this.matchInfo = {};
    }
    setItems(items) {
        var me = this;
        try {
            me.pageIndex = 0;
            me.lastTime = (new Date()).getTime();
            me.items = items;
        } catch (er) {
            console.log(er)
        }
    }
    get dispItems() {
        var me = this;
        var res = [];
        try {
            var nowTm = (new Date()).getTime();
            var dltTime = nowTm - me.lastTime;
            if (dltTime >= me.timeout) {
                var maxPage = Math.ceil(me.items.length * 1.0 / me.pageSize);
                var index = me.pageIndex + 1;
                if (index >= maxPage) {
                    index = 0;
                }
                me.pageIndex = index;
                me.lastTime = nowTm;
            }
            var pos = me.pageIndex * me.pageSize;
            var end = pos + me.pageSize;
            end = end >= me.items.length ? me.items.length : end;
            for (var i = pos; i < end; i = i + 1) {
                res.push(me.items[i])
            }
        } catch (error) {
            console.log(error)
        }
        return res;
    }
}
class TTsJumpLed {
    constructor(_api) {
        this.api = _api;
        this.tplDatas = {
            times: {
                dev: (new Date()).getTime(),
                local: (new Date()).getTime(),
            },
            tplCmd: "",
            tplCode: "",
            matchInfo: {},
            result: {
                settings: {
                    t0: {},
                    t1: {},
                    t2: {},
                },
                info: {},
                ranks: []
            },
            tsInfo: {},
            items: {
                schedule: new TTsJumpLedPaging(),
                startList: new TTsJumpLedPaging(),
                rank: new TTsJumpLedPaging(),
                medal: new TTsJumpLedPaging(),
            },
        };
        this.dicts = {
            tplCodes: {
                welcome: "welcome",
                startList: "startList",
                rank: "rank",
                medal: "medal",
                schedule: "schedule",
                irm: "irm",
                regcomp: "regcomp",
                real: "real",
                result: "result",
            }
        };
        this.lastMsg = {};
    }
    setTplData(msg) {
        var me = this;
        return new Promise((su, fa) => {
            try {
                me.lastMsg = msg;
                me.tplDatas.times.dev = msg.devTime;
                me.tplDatas.times.local = (new Date()).getTime();
                me.tplDatas.tplCmd = msg.tplCmd;
                me.tplDatas.tplCode = me.dicts.tplCodes[msg.tplCmd];

                var matchInfo = msg.params.matchInfo;
                if (matchInfo && matchInfo != null && matchInfo.matchId > 0) {
                    me.tplDatas.matchInfo = matchInfo;
                }

                var cmd = msg.tplCmd;
                if (cmd == 'welcome') {
                    su();
                } else if (cmd == 'schedule') {
                    me.updateSchedule(msg).then(_ => {
                        su();
                    })
                } else if (cmd == 'startList' || cmd == 'rank' || cmd == 'medal') {
                    me.updateItems(msg).then(_ => {
                        su();
                    })
                } else if (cmd == 'regcomp') {
                    var resultId = msg.params.resultId;
                    me.tplDatas.result.ranks = [];
                    me.getResultInfoSettings(resultId).then(_res => {
                        me.tplDatas.result.info = _res.resultInfo;
                        me.tplDatas.result.settings = _res.settings;
                        return me.getResultRanks(resultId);

                    }).then(_res => {
                        me.tplDatas.result.ranks = _res;
                        su();
                    })
                } else if (cmd == 'real' || cmd == 'end' || cmd == 'result') {
                    me.tplDatas.tsInfo = msg.params.tsInfo;
                    var resultId = msg.params.resultId;
                    var endFlag = -1;
                    var updateRank = () => {
                        if (cmd == 'end') {
                            endFlag = 1;
                        } else if (cmd == 'result') {
                            endFlag = 0;
                        }
                        if (endFlag >= 0) {
                            me.getResultRanks(resultId, endFlag).then(_res => {
                                me.tplDatas.result.ranks = _res;
                                su();
                            })
                        } else {
                            su();
                        }
                    };
                    if (resultId == me.tplDatas.result.info.resultId) {
                        endFlag = 0;
                        updateRank();
                    } else {
                        me.getResultInfoSettings(resultId).then(_res => {
                            me.tplDatas.result.info = _res.resultInfo;
                            me.tplDatas.result.settings = _res.settings;
                            updateRank();
                        })

                    }

                } else {
                    su();
                }
            } catch (error) {
                console.log(error);
                su();
            }
        })
    }
    getResultInfoSettings(resultId) {
        var me = this;
        var res = {
            resultInfo: {},
            settings: {}
        };
        return new Promise((su, fa) => {
            try {
                me.api.query('getTsResult', { resultId: resultId }).then(_res => {
                    var resInfo = _res.recordset[0];
                    res.resultInfo.matchId = resInfo.curMatchId;
                    res.resultInfo.matchCode = resInfo.curMatchCode;
                    res.resultInfo.matchName = resInfo.curMatchName;
                    res.resultInfo.matchNameEn = resInfo.curMatchNameEn;
                    res.resultInfo.orgId = resInfo.orgId;
                    res.resultInfo.orgCode = resInfo.orgCode;
                    res.resultInfo.orgName = resInfo.orgName;
                    res.resultInfo.orgNameEn = resInfo.orgNameEn;
                    res.resultInfo.athOrder = resInfo.spResOrder1;
                    res.resultInfo.athName = resInfo.athName;
                    res.resultInfo.athNameEn = resInfo.athNameEn;
                    res.resultInfo.horseBib = resInfo.horseBib;
                    res.resultInfo.horseName = resInfo.horseName;
                    res.resultInfo.horseNameEn = resInfo.horseNameEn;
                    res.settings = {
                        t0: JSON.parse(resInfo.spSettingInfoJson0),
                        t1: JSON.parse(resInfo.spSettingInfoJson1),
                        t2: JSON.parse(resInfo.spSettingInfoJson2),
                    };
                    su(res);
                })
            } catch (error) {
                console.log(error);
                su(res);
            }
        })
    }
    getResultRanks(resultId, flag = 0) {
        var me = this;
        return new Promise((su, fa) => {
            try {

                su([]);
            } catch (error) {
                console.log(error);
                su([]);
            }
        })
    }
    updateResultById(resultId) {
        var me = this;
        return new Promise((su, fa) => {
            try {
                su();
            } catch (error) {
                console.log(error);
                su();
            }
        })
    }
    updateResultRank(resultId) {
        var me = this;
        return new Promise((su, fa) => {
            try {
                su();
            } catch (error) {
                console.log(error);
                su();
            }
        })
    }
    updateSchedule(msg) {
        var me = this;
        return new Promise((su, fa) => {
            try {
                me.tplDatas.items.schedule.items = [];
                me.api.execProc('Proc_Scb_Schedule', { matchDate: msg.params.scheduleDate }).then(_res => {
                    me.tplDatas.items.schedule.items = _res.recordset;
                    su();
                })
            } catch (error) {
                console.log(error);
                su();
            }
        })
    }
    updateItems(msg) {
        var me = this;
        return new Promise((su, fa) => {
            try {
                var procNames = {
                    startList: 'Proc_Scb_StartListIndv'
                };
                var proc = procNames[msg.tplCmd];
                me.api.execProc(proc, { matchId: msg.params.matchId }).then(_res => {
                    me.tplDatas.items[msg.tplCmd].matchInfo = _res.recordset[0];
                    me.tplDatas.items[msg.tplCmd].items = _res.datasetList[1];
                    console.log(me.tplDatas.items);
                    su();
                })
                su();
            } catch (error) {
                console.log(error);
                su();
            }
        })
    }
}







export { TTsJumpCore, tsUtils, TTsJumpLed }